package com.itlong.cloud.app.service.impl;

import com.itlong.cloud.POJO.DTO.app.AppApplyRoomCertificationDTO;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.property.AppUserGetUserDetailsDTO;
import com.itlong.cloud.POJO.DTO.property.AppUserRoomDTO;
import com.itlong.cloud.POJO.DTO.property.ExamineHouseHoldDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppCallElevatorRecordVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorFloorSimpleVO;
import com.itlong.cloud.POJO.VO.app.AppRoomApplyLogVO;
import com.itlong.cloud.POJO.VO.app.AppRoomOwnerInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppHomeDao;
import com.itlong.cloud.app.dao.IAppPadFaceDao;
import com.itlong.cloud.app.service.IAppHomeService;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.HouseHoldJPushSceneTypeEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.RoomCertificateTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.property.dao.*;
import com.itlong.cloud.property.service.IPropertyHouseHoldInfoService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <desc>
 *     新版APP的首页版块服务层实现类
 * </desc>
 *
 * @createDate 2017/9/30
 */
@Service
public class AppHomeServiceImpl implements IAppHomeService{
    private static final Logger LOG = LoggerFactory.getLogger(AppHomeServiceImpl.class);

    @Autowired
    IPropertyAppUserProjectDao iPropertyAppUserProjectDao;

    @Autowired
    IPropertyAppUserRoomDao iPropertyAppUserRoomDao;

    @Autowired
    IPropertyAppAuthRelationsDao iPropertyAppAuthRelationsDao;

    @Autowired
    IAppHomeDao iAppHomeDao;

    @Autowired
    IAppPadFaceDao iAppPadFaceDao;

    @Autowired
    RedisService redisService;

    @Autowired
    IPropertyUserInfoDao iPropertyUserInfoDao;

    @Autowired
    IPropertyHouseHoldInfoService iPropertyHouseHoldInfoService;

    //App用户信息数据库访问对象
    @Autowired
    private IPropertyAppUserInfoDao iPropertyAppUserInfoDao;
    /**
     * <desc>
     *      APP端_首页版块根据房间ID获取房间业主的电话号码
     * </desc>
     * @param roomId 房间ID
     * @return  房间业主的手机号
     * @throws Exception
     * @createDate 2017/9/30
     * @author cuiduanwu
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public String getOwnerPhoneNumber(String roomId) throws  Exception{
        Map<String,Object> params = new HashMap<>();
        params.put("roomId",roomId);
        return  iPropertyAppUserRoomDao.getOwnerPhoneNoInRoom(params);
    }

    /**
     * <desc>
     *      根据房间编号获取房间类型
     * </desc>
     * @param roomId 房间ID
     * @return
     * @throws Exception
     * @createDate 2019/5/21
     * @author Qiang.S
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public String getRoomTypeByroomId(String roomId) throws  Exception{
        return  iPropertyAppUserRoomDao.getRoomTypeByroomId(roomId);
    }

    /**
     * <desc>
     *     APP端_首页版块,用户提交房屋认证申请
     * </desc>
     * @param appApplyRoomCertificationDTO 用户提交申请房屋认证数据
     * @return
     * @createDate 2017/9/30
     * @author cuiduanwu
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public MessageVO applyRoomCertification(AppApplyRoomCertificationDTO appApplyRoomCertificationDTO) throws  Exception{
        MessageVO messageVO = null;
        try {
            //获取项目住户审核配置 //住户审核模式 1开启（人工审核） 0关闭（自动审核）
            String houseAuthMode = iPropertyAppUserProjectDao.getHouseAuthModeByProjectId(appApplyRoomCertificationDTO.getProjectId());
            ProjectPO projectPO = iPropertyAppUserProjectDao.getOne(appApplyRoomCertificationDTO.getProjectId());
            //获取
            Integer userRoomStatus;
            Integer dataSource = null;
            //当①房屋认证类型为业主认证②认证身份为非业主③未开启物业二次认证时，用户房屋状态直接为迁入
            if (StringUtils.isNotBlank(appApplyRoomCertificationDTO.getCertificationType())
                    && !"1".equals(appApplyRoomCertificationDTO.getApplyHouseType())
                    && 0 == projectPO.getRecheckStatus()
                    && RoomCertificateTypeEnum.HOUSER_CERTIFIFATE.getType().toString().equals(appApplyRoomCertificationDTO.getCertificationType())){
                userRoomStatus = 2;
                //直接迁入时变更用户项目中dataSource的值
                dataSource = 2;
            }else {
                //否则根据住户审核模式决定用户的房屋状态
                userRoomStatus = houseAuthMode.equals("1")?1:2;
            }

            Map<String,Object> params = new HashMap<>();
            params.put("projectId",appApplyRoomCertificationDTO.getProjectId());
            params.put("buildId",appApplyRoomCertificationDTO.getBuildId());
            params.put("unitId",appApplyRoomCertificationDTO.getUnitId());
            params.put("roomNum",appApplyRoomCertificationDTO.getRoomNum());
            if (!"1".equals(appApplyRoomCertificationDTO.getApplyHouseType()) && StringUtils.isNotBlank(appApplyRoomCertificationDTO.getOwnerPhoneNo())){ //申请人非业主，核实房间业主信息是否一致
                params.put("ownerPhoneNo",appApplyRoomCertificationDTO.getOwnerPhoneNo());
                AppRoomOwnerInfoVO roomOwnerInfo = iPropertyAppUserRoomDao.checkRoomOwner(params);
                //对应房间是否存在有效的业主
                if(!"1".equals(roomOwnerInfo.getUserProjectStatus())){
                    //LOG.info("【APP_首页版块】用户提交房屋认证时业主被冻结");
                    return new MessageVO(AppErrorCodeEnum.USER_ROOM_FREEZE.getErrorCode());
                }
                if (StringUtils.isBlank(roomOwnerInfo.getParentUserId())){
                    //LOG.info("【APP_首页版块】用户提交房屋认证时业主手机号有误");
                    return new MessageVO(AppErrorCodeEnum.ROOM_OWNER_PHONE_ERROR.getErrorCode());
                }
            }else if("1".equals(appApplyRoomCertificationDTO.getApplyHouseType())) {
                //检查房间业主是否已存在
                Integer ownerCount = iPropertyAppUserRoomDao.countRoomOwner(params);
                if (ownerCount>0){
                    //LOG.info("【APP_首页版块】用户提交房屋认证时申请业主失败，房间业主已存在");
                    return new MessageVO(AppErrorCodeEnum.ROOM_OWNER_IS_EXIST.getErrorCode());
                }
            }
            //检查房间人数是否已达上限
            Integer authMaxNum = iPropertyAppUserProjectDao.getProjectAuthNum(appApplyRoomCertificationDTO.getProjectId());
            //办公人数
            Integer officeAuthMaxNum = iPropertyAppUserProjectDao.getProjectAuthNumByOffice(appApplyRoomCertificationDTO.getProjectId());
            //获取该房屋类型 1住宅 2办公
            Integer housesType = iPropertyUserInfoDao.getHousesType(appApplyRoomCertificationDTO.getRoomId(),appApplyRoomCertificationDTO.getProjectId());
            if(officeAuthMaxNum==0){
                officeAuthMaxNum=11;
            }
            if (authMaxNum==null||authMaxNum==0){
                authMaxNum = 10;
            }
            Integer countUserInRoom = iPropertyAppUserRoomDao.countRoomUser(params);
            if (countUserInRoom==null){
                countUserInRoom = 0;
            }
            if (housesType==1 && countUserInRoom>=authMaxNum){
                return new MessageVO(AppErrorCodeEnum.ROOM_NUM_IS_FULL.getErrorCode());
            }
            if (housesType==3 && countUserInRoom>=officeAuthMaxNum){
                return new MessageVO(AppErrorCodeEnum.ROOM_NUM_IS_FULL.getErrorCode());
            }

            AppUserRoomPO appUserRoomPO = new AppUserRoomPO(appApplyRoomCertificationDTO.getUserId(),
                    appApplyRoomCertificationDTO.getProjectId(),appApplyRoomCertificationDTO.getBuildId(),
                    appApplyRoomCertificationDTO.getUnitId(),appApplyRoomCertificationDTO.getRoomNum(),appApplyRoomCertificationDTO.getRoomId(),
                    userRoomStatus,Integer.parseInt(appApplyRoomCertificationDTO.getApplyHouseType()),2,1,new Date());
            appUserRoomPO.setUpdateTime(new Date());

            AppUserRoomPO preAppUserRoomPO = iPropertyAppUserRoomDao.getPreUserRoom(appUserRoomPO);
            if (preAppUserRoomPO != null){
                if (preAppUserRoomPO.getStatus()==1){
                    if (preAppUserRoomPO.getUserRoomStatus()==1){ //待审核
                        //LOG.info("【APP_首页版块】用户提交房屋认证失败，正在审核，不能重复申请");
                        return new MessageVO(AppErrorCodeEnum.USER_ROOM_NO_CHECK.getErrorCode());
                    }else if (preAppUserRoomPO.getUserRoomStatus() == 2){ //已迁入
                        //LOG.info("【APP_首页版块】用户提交房屋认证失败，用户账号下房间已存在");
                        return new MessageVO(AppErrorCodeEnum.USER_EXIST_IN_ROOM.getErrorCode());
                    }else if (preAppUserRoomPO.getUserRoomStatus() == 3){ //迁出
                        //LOG.info("【APP_首页版块】用户提交房屋认证，用户的房间已被迁出，转为待审核");
                    }else if (preAppUserRoomPO.getUserRoomStatus() == 4){ //审核未通过
                        //LOG.info("【APP_首页版块】用户提交房屋认证失败，用户的房间审核未通过，转为待审核");
//                        return new MessageVO(AppErrorCodeEnum.USER_ROOM_NO_PASS.getErrorCode());
                    }
                }else {
                    LOG.info("【APP_首页版块】用户提交房屋认证，用户的房间处于删除或禁用，转为正常待审核");
                }
            }
            AppUserProjectPO aupVO = new AppUserProjectPO(appApplyRoomCertificationDTO.getUserId(),appApplyRoomCertificationDTO.getProjectId());
            Integer aupResult = 0;
            AppUserProjectPO preAppUserProjectPO = iPropertyAppUserProjectDao.getPreUserProject(aupVO);
            if (preAppUserProjectPO != null){  //更新，转换人与项目处于正常启用

                //app直接选择项目创建的用户项目关系，不再物业系统中展示该用户
                if (aupVO.getDataSource() != null && aupVO.getDataSource() == 1 && dataSource != null && dataSource == 2){
                    aupVO.setDataSource(dataSource);
                }
                aupResult = iPropertyAppUserProjectDao.updatePreUserProject(aupVO);
            }else { //新增
                AppUserProjectPO appUserProjectPO = new AppUserProjectPO(appApplyRoomCertificationDTO.getUserId(),appApplyRoomCertificationDTO.getProjectId(),"0","000000","1",1,1,new Date());
                appUserProjectPO.setUpdateTime(new Date());
                aupResult = iPropertyAppUserProjectDao.save(SqlUtil.durableData(appUserProjectPO, PlatformConstants.TABLE_SAVE));
            }

            if (aupResult>0){
                Integer aurResult = 0;
                if (preAppUserRoomPO != null){ //更新,注册正常待审核
                    aurResult = iPropertyAppUserRoomDao.updatePreUserRoom(preAppUserRoomPO.getId(),Integer.parseInt(appApplyRoomCertificationDTO.getApplyHouseType()), userRoomStatus);
                }else { //新增
                    aurResult = iPropertyAppUserRoomDao.save(SqlUtil.durableData(appUserRoomPO, PlatformConstants.TABLE_SAVE));
                }
                //LOG.info("【APP用户提交房屋自动认证模式】:"+houseAuthMode);
                if (aurResult>0){
                    Map resultMap = new HashMap();
                    resultMap.put("homeAuthMode",houseAuthMode);
                    if(houseAuthMode.equals("0")){
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("userId", appApplyRoomCertificationDTO.getUserId());
                        paramsMap.put("projectId", appApplyRoomCertificationDTO.getProjectId());
                        AppUserGetUserDetailsDTO appUserGetUserDetailsDTO = iPropertyAppUserInfoDao.getUserById(paramsMap);
                        ExamineHouseHoldDTO examineHouseHoldDTO = new ExamineHouseHoldDTO();
                        BeanUtils.copyProperties(appUserGetUserDetailsDTO,examineHouseHoldDTO);
                        examineHouseHoldDTO.setUserRoomStatus(2);
                        List<AppUserRoomDTO> appUserRoomDTOS = new ArrayList<>();
                        AppUserRoomDTO roomDTO = new AppUserRoomDTO();
                        params.put("buildId",appApplyRoomCertificationDTO.getBuildId());
                        params.put("unitId",appApplyRoomCertificationDTO.getUnitId());
                        params.put("roomNum",appApplyRoomCertificationDTO.getRoomNum());
                        roomDTO.setBuildId(appApplyRoomCertificationDTO.getBuildId());
                        roomDTO.setUnitId(appApplyRoomCertificationDTO.getUnitId());
                        roomDTO.setRoomNum(appApplyRoomCertificationDTO.getRoomNum());
                        roomDTO.setRoomId(appApplyRoomCertificationDTO.getRoomId());
                        roomDTO.setHouserType(Integer.parseInt(appApplyRoomCertificationDTO.getApplyHouseType()));
                        appUserRoomDTOS.add(roomDTO);
                        examineHouseHoldDTO.setAppUserRoomDTOS(appUserRoomDTOS);
                        examineHouseHoldDTO.setSourceSystem(appApplyRoomCertificationDTO.getSourceSystem());
                        examineHouseHoldDTO.setInstructionType(appApplyRoomCertificationDTO.getInstructionType());
                        new Thread(() ->  {
                            try {
                                Thread.sleep(1000);
                                iPropertyHouseHoldInfoService.examineUser(examineHouseHoldDTO, projectPO.getIsSmartCommunity(), appApplyRoomCertificationDTO.getProjectId(), appApplyRoomCertificationDTO.getUserId(), HouseHoldJPushSceneTypeEnum.HOUSEHOLD_J_PUSH_SCENE_TYPE_PASS.getType());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).start();

                    }
                    //非自动审批且认证方式为物业认证
                    if ("1".equals(houseAuthMode) &&
                            !RoomCertificateTypeEnum.HOUSER_CERTIFIFATE.getType().toString().equals(appApplyRoomCertificationDTO.getCertificationType())){
                        //创建一条系统消息
                        //查看该项目是否有一条未读的用户审批提醒消息
                        PropertyCloudServiceCostMessageInfoPO messageInfoPO = iPropertyUserInfoDao.getMessage(appApplyRoomCertificationDTO.getProjectId());
                        if (messageInfoPO == null){
                            Integer userCount = iPropertyUserInfoDao.getProjectCheckCount(appApplyRoomCertificationDTO.getProjectId());
                            messageInfoPO = new PropertyCloudServiceCostMessageInfoPO();
                            messageInfoPO.setMessageId(LogicIdUtil.bussinessId());
                            messageInfoPO.setProjectId(appApplyRoomCertificationDTO.getProjectId());
                            messageInfoPO.setMark(0);
                            messageInfoPO.setMessageType(2);
                            messageInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                            messageInfoPO.setCreateTime(new Date());
                            messageInfoPO.setUserAmount(userCount.toString());
                            iPropertyUserInfoDao.save(SqlUtil.durableData(messageInfoPO, PlatformConstants.TABLE_SAVE));
                        }
                    }
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),resultMap);
                }else {
                    //LOG.info("【APP_首页版块】用户提交房屋认证时保存用户房间失败");
                    throw   new Exception("【APP_首页版块】用户提交房屋认证时保存用户房间失败");
                }
            }else {
                //LOG.info("【APP_首页版块】用户提交房屋认证时保存用户项目失败");
                throw   new Exception("【APP_首页版块】用户提交房屋认证时保存用户项目失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw   new Exception("【APP_首页版块】用户提交房屋认证时保存失败", e);
        }
    }

    /**
     * <desc>
     *      获取房间申请记录。
     * <desc/>
     *
     * @param  projectId
     * @param  userId
     * @param  pageNum
     * @return
     * @author shengen.T
     * @createDate 2018-03-27
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Page<AppRoomApplyLogVO> getApplyRoomLog(String projectId, String userId, String pageNum) throws Exception{
        //将DTO转换为Map params
        Map<String, Object> params = new HashMap<>();
        //分页类默认pageSize为20
        Page<AppRoomApplyLogVO> page = new Page<>();
        page.getPage().setPageSize("15");
        page.getPage().setCurrentPage(pageNum);
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        params.put("projectId",projectId);
        params.put("userId",userId);
        List<AppRoomApplyLogVO> pageVOS = iAppHomeDao.getApplyRoomLogPage(params);
        //填充返回数据集
        page.setRows(pageVOS,iAppHomeDao.getPageCount(params));
        return page;
    }


    /**
     * <desc>
     *      保存呼梯记录。
     * <desc/>
     *
     * @param  saveDTO
     * @return
     * @author shengen.T
     * @createDate 2018-04-02
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveCallLiftRecord(AppCallLiftSaveDTO saveDTO) throws Exception{
        Integer result = 0;
        if(saveDTO.getMark() != 1){
            CloudElevatorOperateRecordPO recordPO = new CloudElevatorOperateRecordPO();
            recordPO.setRecordId(LogicIdUtil.bussinessId());
            recordPO.setUserId(saveDTO.getUserId());
            recordPO.setDeviceUnique(saveDTO.getDeviceUnique());
            recordPO.setProjectId(saveDTO.getProjectId());
            recordPO.setFromFloor(saveDTO.getFromFloor());
            recordPO.setToFloor(saveDTO.getToFloor());
            recordPO.setCreateTime(new Date());
            recordPO.setUpdateTime(new Date());
            recordPO.setPassTime(new Date());
            recordPO.setStatus(1);
            recordPO.setSource(saveDTO.getSource());
            redisService.set(RedisConstant.REDIS_ROBOT_NONINDUCTIVE_CALL_RECORD_CACHE+
                            saveDTO.getUserId(),RedisConstant.REDIS_ROBOT_NONINDUCTIVE_CALL_RECORD_CACHE_TIME,
                    recordPO.getRecordId());
            result = iAppHomeDao.saveCallElevatorRecord(SqlUtil.durableData(recordPO, PlatformConstants.TABLE_SAVE));
            if(result>0){
                CloudElevatorCallStatusPO callStatusPO = new CloudElevatorCallStatusPO();
                callStatusPO.setCallId(LogicIdUtil.bussinessId());
                callStatusPO.setRecordId(recordPO.getRecordId());
                callStatusPO.setGroupConId(saveDTO.getGroupConId());
                callStatusPO.setDeviceUnique(saveDTO.getDeviceUnique());
                callStatusPO.setFromFloor(saveDTO.getFromFloor());
                callStatusPO.setToFloor(saveDTO.getToFloor());
                callStatusPO.setFromStatus(0);
                callStatusPO.setToStatus(0);
                callStatusPO.setOperateStatus(1);
                callStatusPO.setStatus(1);
                callStatusPO.setCreateTime(new Date());
                callStatusPO.setUpdateTime(new Date());
                callStatusPO.setAppRead(0);
                iAppHomeDao.saveCallLiftStatusInfo(SqlUtil.durableData(callStatusPO, PlatformConstants.TABLE_SAVE));
            }
        }
        if(StringUtils.isNotBlank(saveDTO.getCorrelationId())){
            TimeTaskDevicePassRecordPO po = iAppHomeDao.getDevicePassRecordByCorrelationId(saveDTO.getCorrelationId());
            if (po != null && saveDTO.getCorrelationId().equals(po.getCorrelationId())) {
                //此时说明已经保存了蓝牙通行方式
                //当IOT通行方式已经入库，需将能行方式改为 蓝牙+IOT 并推送给一卡通
                iAppHomeDao.updateOpenType(po.getCorrelationId());
                //此处需注意处理 有可能通行记录已同步至设备子表中，故需在此处理子表通行方式
                iAppHomeDao.updateElevatorOpenType(po.getDeviceUnique(), DateUtil.fomatDate(po.getPassTime()),saveDTO.getUserId());
                return 1;
            }
        }
        //保存通行记录
        //验证是否是完整信息
        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
        po.setPdId(LogicIdUtil.bussinessId());
        po.setUserId(saveDTO.getUserId());
        po.setProjectId(saveDTO.getProjectId());
        po.setDeviceUnique(saveDTO.getDeviceUnique());
        po.setPassTime(new Date());
        po.setDeviceType(PropertyEquipTypeEnum.ELEVATOR.getType());
        //查询设备名称
        if(StringUtils.isBlank(po.getDeviceName()) && StringUtils.isNotBlank(po.getDeviceUnique()) && po.getDeviceType()!=null){
            po.setDeviceName(iAppHomeDao.getDeviceNameByDeviceUnique(po.getDeviceUnique(),po.getDeviceType()));
        }
        po.setOpenType(19);
        po.setOpenCount(1);
        po.setStatus(DataStatusEnum.NORMAL.getType());
        po.setUploadTime(new Date());
        po.setCreateTime(po.getUploadTime());
        po.setSynchro(0);
        po.setIsOpen(0);
        po.setSource(saveDTO.getSource());
        po.setFromFloor(saveDTO.getFromFloor());
        po.setToFloor(saveDTO.getToFloor());
        po.setCorrelationId(saveDTO.getCorrelationId());
        iAppHomeDao.saveCallElevatorRecord(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
        return result;
    }

    /**
     * <desc>
     *      获取呼梯记录。
     * <desc/>
     *
     * @param  userId 用户ID
     * @param  deviceUnique 设备唯一ID
     * @return
     * @author shengen.T
     * @createDate 2018-04-03
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public List<AppCallElevatorRecordVO> getCallElevatorRecord(String userId, String deviceUnique) throws Exception{
        String[] deviceUniques = StringHandlerUtil.splitString(deviceUnique);
        List<AppCallElevatorRecordVO> result=  iAppHomeDao.getCallLiftRecord(userId,deviceUniques);
        if(result!=null&&result.size()>0){
            for (AppCallElevatorRecordVO vo:result){
                AppElevatorFloorSimpleVO floorSimpleVO = iAppHomeDao.getFloorInfo(vo.getDeviceUnique(),vo.getFromId(),vo.getToId());
                if(floorSimpleVO!=null){
                    vo.setFromNum(floorSimpleVO.getFromFloor());
                    vo.setToNum(floorSimpleVO.getToFloor());
                }
            }
        }
        return result;
    }


    /**
     * <desc>
     *      删除呼梯记录。
     * <desc/>
     *
     * @param  userId 用户Id
     * @param  deviceUnique 设备唯一Id
     * @param  projectId 项目编号
     * @return
     * @author shengen.T
     * @createDate 2018-04-04
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deleteCallElevatorRecord(String userId,String deviceUnique,String projectId) throws Exception{
        String deviceUniques[] = StringHandlerUtil.splitString(deviceUnique);
        return iAppHomeDao.deleteCallLiftRecord(userId,projectId,deviceUniques);
    }

    /**
     * <desc>
     *      取消预约呼梯。
     * <desc/>
     *
     * @param  userId 用户Id
     * @param  deviceUnique 设备唯一Id
     * @param  projectId 项目编号
     * @return
     * @author shengen.T
     * @createDate 2018-04-11
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer cancelCallLift(String userId,String deviceUnique,String projectId) throws Exception{
        Map<String,Object> controller = iAppHomeDao.getControllerByDeviceUnique(deviceUnique);
        String groupConId = null;
        if(controller !=null && controller.get("groupConId") != null){
            groupConId = controller.get("groupConId").toString();
            deviceUnique = null;
        }
        String recordId = iAppHomeDao.getRecordIdForUser(userId,projectId,deviceUnique,groupConId);
        return iAppHomeDao.cancelCallLift(recordId);
    }

    /**
     * <desc>
     *      获取真实楼层信息。
     * <desc/>
     *
     * @param deviceUnique 设备唯一编号
     * @param fromId 出发楼层ID
     * @param toId 目标楼层ID
     * @return
     * @author shengen.T
     * @createDate 2018-04-12
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public AppElevatorFloorSimpleVO getRealFloorInfo(String deviceUnique,String fromId,String toId) throws Exception{
        AppElevatorFloorSimpleVO floorVO = iAppHomeDao.getRealFloorInfo(deviceUnique,fromId,toId);
        return floorVO;

    }

    /**
     * <desc>
     *      获取楼层权限标识
     * <desc/>
     *
     * @param deviceUnique 设备唯一编号
     * @param fromId 出发楼层名称
     * @param toId 到达楼层名称
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/29
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Map<String,Object> getNaturalFloor(String deviceUnique,String fromId,String toId) throws Exception{
        return  iAppHomeDao.getNaturalFloor(deviceUnique,fromId,toId);
    }

    /**
     * <desc>
     *      设备验证(梯控)。
     * <desc/>
     *
     * @param projectId 项目编号
     * @param deviceId 项目ID
     * @return
     * @author Qiang.S
     * @createDate 2018-05-14
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer elevatorAuthorityCheck(String projectId,String deviceId) throws Exception{
        return iAppHomeDao.elevatorAuthorityCheck(projectId,deviceId);
    }

    /**
     * <desc>
     *      设备验证(门禁)。
     * <desc/>
     *
     * @param projectId 项目编号
     * @param deviceId 项目ID
     * @return
     * @author Qiang.S
     * @createDate 2018-05-14
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer entranceAuthorityCheck(String projectId,String deviceId) throws Exception{
        return iAppHomeDao.entranceAuthorityCheck(projectId,deviceId);
    }

    /**
     * <desc>
     *      登陆验证。
     * <desc/>
     *
     * @param ID 账号
     * @param password 密码
     * @return
     * @author Qiang.S
     * @createDate 2018-05-14
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer engineerLoginVerify(String ID,String password) throws Exception{
        return iAppHomeDao.engineerLoginVerify(ID,password);
    }

    /**
     * <desc>
     *      批量获取真实楼层信息。
     * <desc/>
     *
     * @param deviceUnique 设备唯一编号
     * @param floorString
     * @return
     * @author shengen.T
     * @createDate 2018-05-18
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public String batchGetRealFloorList(String deviceUnique,String floorString) throws Exception{
        String[] floorList = StringHandlerUtil.splitString(floorString);
        if(StringUtils.isNotBlank(floorString)) {
            List<String> realFloorList = iAppHomeDao.batchGetRealFloorList(deviceUnique, floorList);
            if (realFloorList != null && realFloorList.size() > 0) {
                StringBuilder sb = new StringBuilder("");
                realFloorList.forEach(rf -> {
                    sb.append(rf).append(",");
                });
                String tmp = sb.toString();
                return tmp.substring(0, tmp.length() - 1);
            }
        }
        return null;
    }

    /**
     * <desc>
     *      检测用户是否在项目下。
     * <desc/>
     *
     * @param userId 用户编号
     * @param projectId 项目编号
     * @return
     * @author shengen.T
     * @createDate 2018-05-29
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Map<String,Object> checkUserInProject(String userId,String projectId){
        Map<String,Object> res = new HashMap<>();
        Integer isProject =  iAppHomeDao.checkUserInProject(userId,projectId);
        Map userInfo = iAppHomeDao.getUserStatus(userId,projectId);
        Integer projectStatus = iAppPadFaceDao.checkProjectForbidden(projectId);
        if (userInfo == null) {
            userInfo = new HashMap();
        }
        res.put("userProjectStatus",isProject);
        if(null!=userInfo){
            res.put("userStatus",(null==userInfo.get("status"))?"":userInfo.get("status").toString());
            res.put("userName",(null==userInfo.get("userName"))?"":userInfo.get("userName").toString());
        }else{
            res.put("userStatus","");
            res.put("userName","");
        }
        res.put("projectStatus",projectStatus);
        return res;
    }

    /**
     * <desc>
     *      根据人脸获取访客名称。
     * <desc/>
     *
     * @param userId 用户编号
     * @param projectId 项目编号
     * @return
     * @author Qiang.S
     * @createDate 2019-05-16
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public String getVisitorName(String userId,String projectId){
        return iAppHomeDao.getVisitorName(userId,projectId);
    }
}
